package trism.game.model.common.stat.cells {

	/**
	 * @author Samoiloff  http://samoiloff.com/
	 */
	public class CellsItem {
		
		public static const SIDE		: int = 60;
		public static var SIDE2			: Number;
		public static var MEDIAN		: Number;
		public static var MEDIAN3		: Number;
		
		private var _xyArr:Array;
		
		private var _width:int;
		private var _height:int;
		
		public function CellsItem(width:int, height:int) {
			SIDE2 = SIDE / 2;
			MEDIAN = Math.sqrt(3) * SIDE2;
			MEDIAN3 = MEDIAN /3;
			
			_width = width;
			_height = height;
			
			_xyArr = new Array(_width * _height);

			for (var y : int = 0; y < _height; y++) {
				for (var x : int = 0; x < _width; x++) {
					var cellItem : CellItem = new CellItem();
					cellItem.update(x, y);
					setAtXY(cellItem, x, y);
				}
			}
		}
		
		public function get length() : int {
			return _xyArr.length;
		}
		
		public function getItemAt(i : int) : CellItem {
			return _xyArr[i] as CellItem;
		}
		
		public function setAtXY(cellItem : CellItem, x : int, y : int) : void {
			_xyArr[_width * y + x] = cellItem;
		}
		
		public function getByIndex(i : int) : CellItem {
			return _xyArr[i] as CellItem;
		}
		
		public function getAtXY(x : int, y : int) : CellItem {
			return _xyArr[_width*y + x] as CellItem;
		}
		
		public function getNextCell(targetCell:CellItem, direction:int):CellItem {
			switch (direction) {
				case CellDirection.DN_RIGHT: 
					if (targetCell.headRight) {
						return getAtXY(targetCell.x, targetCell.y+1);
					} else {
						return getAtXY(targetCell.x + 1, targetCell.y);
					}
					break;
				case CellDirection.UP:
					return getAtXY(targetCell.x, targetCell.y-1);
					break;
				case CellDirection.UP_RIGHT:
					if (targetCell.headRight) {
						return getAtXY(targetCell.x, targetCell.y-1);
					} else {
						return getAtXY(targetCell.x+1, targetCell.y);
					}
					break;
				case CellDirection.UP_LEFT:
					if (targetCell.headRight) {
						return getAtXY(targetCell.x-1, targetCell.y);
					} else {
						return getAtXY(targetCell.x, targetCell.y-1);
					}
					break;
				case CellDirection.DN:
					return getAtXY(targetCell.x, targetCell.y+1);
					break;
				case CellDirection.DN_LEFT:
					if (targetCell.headRight) {
						return getAtXY(targetCell.x-1, targetCell.y);
					} else {
						return getAtXY(targetCell.x, targetCell.y-1);
					}
				break;
			}
			return null;
		}
	}
}
